package com.example.wxchatdemo.Files;


import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import com.example.wxchatdemo.MainActivity;
import com.example.wxchatdemo.R;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.LinkedList;
import java.util.List;

public class MainFiles extends AppCompatActivity {
    private List<FileListPojo> mData = null;
    private Context mContext;
    private FilesShowAdapter mAdapter = null;
    //图片适配器
    private LinkedList<String> mData_imgs;
    private ImgsAdapter imgsAdapter=null;


//页面元素
    private Button btnsubmit;
    private Button btnget;
    private Button btnpath;
    private Button upPath;
    private Button mysocket;
    private ListView listview;
    private ListView listview_imgs;
    //socket配置
    private Socket sockets;
    private String address="100.2.33.224";
    //
    private String File_Path;

    public String getFile_Path() {
        return File_Path;
    }

    public void setFile_Path(String file_Path) {
        File_Path = file_Path;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        //设置默认路径
        setFile_Path("/storage/emulated/0/AppFiles/");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mainfiles_layout);
        mContext=MainFiles.this;

        btnsubmit=(Button) findViewById(R.id.btnSubmit);
        btnget=(Button) findViewById(R.id.btnget);
        btnpath=(Button) findViewById(R.id.btnpath);
        mysocket=(Button) findViewById(R.id.mysocket);
        upPath=(Button) findViewById(R.id.upPath);
        listview=(ListView) findViewById(R.id.listview);
        listview_imgs=(ListView) findViewById(R.id.imgs_listview);
        //图片list
        mData_imgs=new LinkedList<String>();
//获取和发送文件
        btnsubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Thread thread=new Thread(new Runnable() {
                    @Override
                    public void run() {
                        System.out.println("线程启动了");
                        putfiles putfiles=new putfiles();
                        try {

                            putfiles.putfiles_one();
                        } catch (IOException e) {

                        }
                    }
                });
                thread.start();


            }
        });

//获取文件
        btnget.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Thread thread=new Thread(new Runnable() {
                    @Override
                    public void run() {

                        try {
                            Socket socketss=new Socket(address,8089);
                            OutputStream outputStream = socketss.getOutputStream();
                            outputStream.write(new String("niniiiii-sent").getBytes());
                            outputStream.close();
                            socketss.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                            System.out.println("----");
                        }

                    }
                });
                thread.start();


                //    Toast.makeText(MainActivity.this, "点我干嘛？", Toast.LENGTH_SHORT).show();



            }
        });

//获取相册
        btnpath.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MainFiles.this.runOnUiThread(new Runnable() {
                    public void run() {

                        setFile_Path("/storage/emulated/0/DCIM/Camera/");
                        showFilePath(getFile_Path());


                    }
                });

            }
        });

//回到默认文件夹
        mysocket.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MainFiles.this.runOnUiThread(new Runnable() {
                    public void run() {
                        setFile_Path("/storage/emulated/0/AppFiles/");
                        System.out.println("打开默认文件夹");
                        showFilePath(getFile_Path());
                    }
                });

            }
        });
//返回上一级目录
        upPath.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MainFiles.this.runOnUiThread(new Runnable() {
                                                    public void run() {

                                                        String[] splitss = getFile_Path().split("/");
                                                        if (splitss.length==2){
                                                            System.out.println("文件以到终点");
                                                            return;
                                                        }

                                                        splitss[splitss.length - 1] = "";
                                                        String PATH = "";
                                                        for (int i = 0; i < splitss.length; i++) {
                                                            if (splitss[i] != "") {
                                                                PATH = PATH + splitss[i] + "/";
                                                            }
                                                        }
                                                        System.out.println("PATH====" + PATH );
                                                        setFile_Path(PATH);
                                                        showFilePath(getFile_Path());

                                                    }

                                                }
                );

            }
        });
//为发送文件list添加点击时间
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int index, long l) {
                //文件名
                String Filename= mData.get(index).getFileName();
                System.out.println("获取当前点击的文件"+Filename);
                //点击了文件
                if (Filename.contains(".")){
                    MainFiles.this.runOnUiThread(new Runnable() {
                        public void run() {
                            // imageView.setImageURI(Uri.fromFile(new File("/storage/emulated/0/AppFiles/"+Filename)));

                            mData_imgs.add(new String(getFile_Path()+Filename));
                            imgsAdapter=new ImgsAdapter(mData_imgs,mContext);
                            listview_imgs.setAdapter(imgsAdapter);

                            //打开文件
                            Thread thread = new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        sent_file(Filename + "-sent");
                                    } catch (IOException e) {
                                        //
                                        System.out.println("点击listview，发送文件失败了--167--Main");
                                    }
                                }
                            });
                            thread.start();
                        }
                    });

                }else{
//点击了文件夹
                    String[] strings=getFile_Path().split("/");
                    for (int i=0;i<strings.length;i++){
                    }
                    String f="";
                    for (int i=0;i<strings.length;i++){
                        f=f+strings[i]+"/";
                    }
                    System.out.println("点击listview-最后拼接好的----"+f+Filename+"/");
                    setFile_Path(f+Filename+"/");
                    MainFiles.this.runOnUiThread(new Runnable() {
                        public void run() {
                            showFilePath(getFile_Path());
                        }});

                }


            }
        });
    }


//根据文件路径发送文件到服务器
    public void sent_file(String filename) throws IOException {
        InputStream is=null;
        OutputStream os=null;
        Socket socket=null;
        FileInputStream fileInputStream=null;

        try{
            socket=new Socket(address,8089);
            if (socket!=null){
                is = socket.getInputStream();
                os= socket.getOutputStream();
            }
        }catch (Exception E){
            System.out.println("连接异常-199-MAin");
        }
        //发送文件名
        byte[] bytes1 = filename.getBytes();
        os.write(bytes1);
        String[] split=filename.split("-");
        //发送文件
        File file=new File(getFile_Path()+"/"+split[0]);
        System.out.println("--");
        fileInputStream=new FileInputStream(file);
        System.out.println(file.length()+"是文件大小+需要发送"+(int)file.length()/4096);
        byte[] bytes=new byte[4096];
        int sive=0;
        int xxx=1;
        while ((sive=fileInputStream.read(bytes))!=-1){
            //发送byte数组到服务器
            os.write(bytes,0,sive);
            xxx++;
        }
        if (os != null) {
            os.flush();
            //os.close();/*这里不能这么使用，不然后面的socket就已经关闭了，导致服务器端的socket接收不完整，会卡在read（byte）里*/
            socket.shutdownOutput();
        }
        if (fileInputStream!=null){
            fileInputStream.close();

        }
        if (!socket.isClosed()){
            System.out.println("文件发送了--关闭阶段"+xxx+"次");
            System.out.println("socket发送文件已关闭");
            Toast.makeText(MainFiles.this, "你好!", Toast.LENGTH_LONG).show();
            // socket.close();/*这里不能这么使用，不然后面的socket就已经关闭了，导致服务器端的socket接收不完整，会卡在read（byte）里*/

        }
    }

//动态获取文件路径
    public void  showFilePath(String Path){
        //listview生成
        mData = new LinkedList<FileListPojo>();
        //获取文件路径里的文件列表
        File directory = new File(Path);
        System.out.println(directory);
        //把每个文件添加到flist上
        File[] fList = directory.listFiles();
        if (fList!=null){
            for (int i=0;i<fList.length;i++){
                //  System.out.println("文件:"+fList[i].getName());
             //   System.out.println(fList[i].getAbsolutePath()+"------绝对路径");
                mData.add(new FileListPojo(fList[i].getName(),fList[i].getAbsolutePath()));
            }
        }else {
            mData.add(new FileListPojo("无法打开文件！","已到达根目录！"));
        }
        mAdapter = new FilesShowAdapter((LinkedList<FileListPojo>) mData, mContext);
        listview.setAdapter(mAdapter);
        System.out.println("设置文件路径成功");
    }


}